package flappy.TienIch;

import flappy.Game.GameWorld;
import flappy.Game.TaiNguyen;
import flappy.VatThe.Chim;
import flappy.VatThe.MatDat;
import flappy.VatThe.OngNuoc;

public class ScrollHandler {
	
	public MatDat     matDat1, matDat2;
	public OngNuoc    ongNuoc1, ongNuoc2, ongNuoc3;
	
	private GameWorld game;
	
	public ScrollHandler(GameWorld game, float yPos) {
		this.game = game;
		matDat1 = new MatDat(0, yPos, 168, 56, TaiNguyen.TocDoThanhCuon);
		matDat2 = new MatDat(matDat1.getTailX(), yPos, 168, 56, TaiNguyen.TocDoThanhCuon);
		
		ongNuoc1 = new OngNuoc(210, 0, 22, 60, TaiNguyen.TocDoThanhCuon, yPos);
		ongNuoc2 = new OngNuoc(ongNuoc1.getTailX() + TaiNguyen.KhoangCachGiua2OngNuoc, 0, 22, 70, TaiNguyen.TocDoThanhCuon, yPos);
		ongNuoc3 = new OngNuoc(ongNuoc2.getTailX() + TaiNguyen.KhoangCachGiua2OngNuoc, 0, 22, 60, TaiNguyen.TocDoThanhCuon, yPos);
	}
	
	public void updateReady(float delta) {
		
		matDat1.update(delta);
		matDat2.update(delta);

		if (matDat1.isScrolledLeft()) {
			matDat1.reset(matDat2.getTailX());
			
		} else if (matDat2.isScrolledLeft()) {
			matDat2.reset(matDat1.getTailX());			
		}
		
	}
	
	public void update(float delta) {
		matDat1.update(delta);
		matDat2.update(delta);
		ongNuoc1.update(delta);
		ongNuoc2.update(delta);
		ongNuoc3.update(delta);
		
		if (ongNuoc1.isScrolledLeft()) {
			ongNuoc1.reset(ongNuoc3.getTailX() + TaiNguyen.KhoangCachGiua2OngNuoc);
		} else if (ongNuoc2.isScrolledLeft()) {
			ongNuoc2.reset(ongNuoc1.getTailX() + TaiNguyen.KhoangCachGiua2OngNuoc);			
		} else if (ongNuoc3.isScrolledLeft()) {
			ongNuoc3.reset(ongNuoc2.getTailX() + TaiNguyen.KhoangCachGiua2OngNuoc);
		}
		
		if (matDat1.isScrolledLeft()) {
			matDat1.reset(matDat2.getTailX());
			
		} else if (matDat2.isScrolledLeft()) {
			matDat2.reset(matDat1.getTailX());			
		}
	}
	
	public void stop() {
		matDat1.stop();
		matDat2.stop();
		ongNuoc1.stop();
		ongNuoc2.stop();
		ongNuoc3.stop();
	}
	
	public boolean KiemTraVaCham(Chim chim) {		
		if (!ongNuoc1.DaAnDiem && ongNuoc1.getX() < chim.x()) {
			game.CongDiem();
			ongNuoc1.DaAnDiem = true;
			TaiNguyen.amThanhAnDiem.play();
		} else if (!ongNuoc2.DaAnDiem && ongNuoc2.getX() < chim.x()) {
			game.CongDiem();
			ongNuoc2.DaAnDiem = true;
			TaiNguyen.amThanhAnDiem.play();
			
		} else if (!ongNuoc3.DaAnDiem && ongNuoc3.getX() < chim.x()) {
			game.CongDiem();
			ongNuoc3.DaAnDiem = true;
			TaiNguyen.amThanhAnDiem.play();
		}		
		return (ongNuoc1.KiemTraVaCham(chim) || ongNuoc2.KiemTraVaCham(chim) || ongNuoc3.KiemTraVaCham(chim));
	}
	
	public void onRestart() {
		matDat1.KhoiTao(0, TaiNguyen.TocDoThanhCuon);
		matDat2.KhoiTao(matDat1.getTailX(), TaiNguyen.TocDoThanhCuon);
		ongNuoc1.KhoiTaoLai(210, TaiNguyen.TocDoThanhCuon);
		ongNuoc2.KhoiTaoLai(ongNuoc1.getTailX() + TaiNguyen.KhoangCachGiua2OngNuoc, TaiNguyen.TocDoThanhCuon);
		ongNuoc3.KhoiTaoLai(ongNuoc2.getTailX() + TaiNguyen.KhoangCachGiua2OngNuoc, TaiNguyen.TocDoThanhCuon);
	}
	
}
